package com.yuntongxun.ecdemo.voicechat.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.loopj.android.http.RequestParams;
import com.yuntongxun.ecdemo.R;
import com.yuntongxun.ecdemo.common.CCPAppManager;
import com.yuntongxun.ecdemo.common.utils.LogUtil;
import com.yuntongxun.ecdemo.storage.ContactSqlManager;
import com.yuntongxun.ecdemo.storage.GroupSqlManager;
import com.yuntongxun.ecdemo.storage.IMessageSqlManager;
import com.yuntongxun.ecdemo.ui.contact.ECContacts;
import com.yuntongxun.ecdemo.ui.group.GroupService;
import com.yuntongxun.ecdemo.voicechat.api.ApiConstants;
import com.yuntongxun.ecdemo.voicechat.bean.Group;
import com.yuntongxun.ecdemo.voicechat.comman.Contants;
import com.yuntongxun.ecdemo.voicechat.listeners.IRecyclerViewItemListener;
import com.yuntongxun.ecdemo.voicechat.listeners.LoadMoreClickListener;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadView;
import com.yuntongxun.ecdemo.voicechat.loading.ILoadViewImpl;
import com.yuntongxun.ecdemo.voicechat.presenter.ICommonRequestPresenter;
import com.yuntongxun.ecdemo.voicechat.presenter.impl.CommonRequestPresenterImpl;
import com.yuntongxun.ecdemo.voicechat.ui.adapter.GroupAdapter;
import com.yuntongxun.ecdemo.voicechat.util.JsonHelper;
import com.yuntongxun.ecdemo.voicechat.util.NetUtils;
import com.yuntongxun.ecdemo.voicechat.util.PreferenceUtils;
import com.yuntongxun.ecdemo.voicechat.util.iview.ICommonViewUi;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.ExStaggeredGridLayoutManager;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.HeaderSpanSizeLookup;
import com.yuntongxun.ecdemo.voicechat.view.headerfooterrecyclerview.OnRecyclerViewScrollListener;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.im.ECGroup;

import java.util.ArrayList;
import java.util.List;

import butterknife.InjectView;
import butterknife.OnClick;

/**
 * 群组
 */

public class GroupListActivity extends BaseVoiceChatActivity implements ICommonViewUi, IRecyclerViewItemListener, LoadMoreClickListener, SwipeRefreshLayout.OnRefreshListener ,
        GroupService.Callback,GroupService.OnApplyGroupCallbackListener{

    @InjectView(R.id.swipe_refresh_layout)
    public SwipeRefreshLayout swipeRefreshLayout;

    @InjectView(R.id.recycler_view)
    public RecyclerView recyclerView;

    private HeaderAndFooterRecyclerViewAdapter adapter;
    private ExStaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<Group> mResultList = new ArrayList<Group>();

    private ICommonRequestPresenter iCommonRequestPresenter = null;

    private ILoadView iLoadView = null;

    private View loadMoreView = null;

    private boolean isRequesting = false;//标记，是否正在刷新

    private int mCurrentPage = 0;

    private ECGroup mGroup;

    //讨论组
    private List<Group> discussionGroups=new ArrayList<>();

    @Override
    protected boolean isBindEventBusHere() {
        return false;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_group_list;
    }

    @Override
    protected void initViewsAndEvents() {
        setTitle("Group Chat");
        setRightTitle("New Group");
        iCommonRequestPresenter = new CommonRequestPresenterImpl(mContext, this);
        GroupService.syncGroup(this);
        GroupService.syncDiscussionGroup(this);
        registerReceiver(new String[]{getPackageName() + ".inited" , IMessageSqlManager.ACTION_GROUP_DEL});
        iLoadView = new ILoadViewImpl(mContext, this);

        loadMoreView = iLoadView.inflate();
        swipeRefreshLayout.setOnRefreshListener(this);
//        recyclerView.addOnScrollListener(new MyScrollListener());

        refreshListView();

        //第一次进来时刷新
        if (NetUtils.isNetworkConnected(mContext)) {
            if (null != swipeRefreshLayout) {

                swipeRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        swipeRefreshLayout.setRefreshing(true);

                        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
                    }
                }, ApiConstants.Integers.PAGE_LAZY_LOAD_DELAY_TIME_MS);
            }
        }
        onSyncGroup();
        discussionGroups.clear();
        Cursor cursor = GroupSqlManager.getGroupCursor(false);
        List<ECGroup> ecGroups=new ArrayList<>();
        try {
            if (cursor != null) {
                while(cursor.moveToNext()){
                    ECGroup ecGroup=new ECGroup();
                    ecGroup.setGroupId(cursor.getString(0));
                    ecGroup.setName(cursor.getString(1));
                    ecGroup.setGroupType(cursor.getInt(2));
                    ecGroup.setCount(cursor.getInt(3));
                    ecGroup.setPermission(ECGroup.Permission.values()[cursor.getInt(4)]);
                    ecGroups.add(ecGroup);

                    Group group=new Group();
                    group.setName(ecGroup.getName());
                    group.setType(Group.DISCUSION);
                    group.setCloopenGroupId(ecGroup.getGroupId());
                    discussionGroups.add(group);
                }

            }
        }catch (Exception e){
            LogUtil.e("e",e.toString());
        }

    }



    public void refreshListView() {

        GroupAdapter mIntermediary = new GroupAdapter(mContext, mResultList, this);

        adapter = new HeaderAndFooterRecyclerViewAdapter(mIntermediary);

        recyclerView.setAdapter(adapter);

//        if (mResultList.size() >= ApiConstants.Request.PAGE_NUMBER) {
//
//            RecyclerViewUtils.setFooterView(recyclerView, loadMoreView);
//        }
        staggeredGridLayoutManager = new ExStaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

        staggeredGridLayoutManager.setSpanSizeLookup(new HeaderSpanSizeLookup((HeaderAndFooterRecyclerViewAdapter) recyclerView.getAdapter(), staggeredGridLayoutManager.getSpanCount()));

        recyclerView.setLayoutManager(staggeredGridLayoutManager);
    }
    public static boolean sync = false;
    @Override
    protected void onResume() {
        super.onResume();
        if(!sync) {
            GroupService.syncGroup(this);
            sync = true;
        }
    }

    @Override
    protected void handleReceiver(Context context, Intent intent) {
        super.handleReceiver(context, intent);
        if(intent.getAction().equals(new String[]{getPackageName() + ".inited"})){
            GroupService.syncGroup(this);
        } else if (IMessageSqlManager.ACTION_GROUP_DEL.equals(intent.getAction())) {
            onSyncGroup();
        }
    }

    @Override
    public void onSyncGroup() {

    }

    @Override
    public void onSyncGroupInfo(String groupId) {

    }

    @Override
    public void onGroupDel(String groupId) {
        onSyncGroup();
    }

    @Override
    public void onError(ECError error) {

    }

    @Override
    public void onUpdateGroupAnonymitySuccess(String groupId, boolean isAnonymity) {

    }

    @Override
    public void onApplyGroup(boolean success) {
        GroupSqlManager.updateJoinStatus(group.getCloopenGroupId() , true);
        // 直接加入
        CCPAppManager.startChattingAction(this ,group.getCloopenGroupId() , group.getName() );
    }

    public class MyScrollListener extends OnRecyclerViewScrollListener {

        @Override
        public void onScrollUp() {

        }

        @Override
        public void onScrollDown() {

        }

        @Override
        public void onBottom() {
            toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
        }

        @Override
        public void onMoved(int distanceX, int distanceY) {

        }
    }

    @Override
    public void onRefresh() {
        toRequest(ApiConstants.EventTags.REFRESH_LIST_EVENT);
    }
    Group group;
    @Override
    public void onItemClick(int position) {
        group=mResultList.get(position);
        if (group.getType()==Group.DISCUSION){
//            Cursor cursor = GroupSqlManager.getGroupCursor(false);
//            DemoGroup dGroup = new DemoGroup();
//            dGroup.setCursor(cursor);
//            if (dGroup.isJoin()) {
                CCPAppManager.startChattingAction(this,
                        group.getCloopenGroupId(), group.getName());
                return;
//            }
//            Intent intent = new Intent(this,
//                    ApplyWithGroupPermissionActivity.class);
//            intent.putExtra(GroupInfoActivity.GROUP_ID, dGroup.getGroupId());
//            startActivity(intent);
        }else{
            List<ECGroup> ecGroups=new ArrayList<>();
            ECGroup ecGroup=new ECGroup();
            ecGroup.setGroupId(group.getCloopenGroupId());
            ecGroup.setName(group.getName());
            ecGroups.add(ecGroup);
            GroupSqlManager.insertGroupInfos(ecGroups, -1);

            mGroup = GroupSqlManager.getECGroup(group.getCloopenGroupId());
            syncGroupInf(group.getCloopenGroupId());
            GroupService.syncGroupInfo(group.getCloopenGroupId());
            GroupService.applyGroup(group.getCloopenGroupId(), "", this);
//            CCPAppManager.startChattingAction(GroupListActivity.this , group.getCloopenGroupId() , group.getName());

        }


    }

    @OnClick(R.id.toolbar_right_title)
    public void onRightClick(){
        startActivity(new Intent(GroupListActivity.this,CreateGroupActivity.class));
    }

    private void syncGroupInf(String groupId) {
        mGroup = GroupSqlManager.getECGroup(groupId);
        if(mGroup == null) {
            return ;
        }

        if(!TextUtils.isEmpty(mGroup.getName())) {
//            mGroupProfileView.setNameText(appTitle = mGroup.getName());
//            getTopBarView().setTopBarToStatus(1, R.drawable.topbar_back_bt, -1, mGroup.getName(), this);
        }
        if(!TextUtils.isEmpty(mGroup.getOwner())) {
            ECContacts contact = ContactSqlManager.getContact(mGroup.getOwner());
            if(contact != null) {
//                mGroupProfileView.setOwnerText(contact.getNickname());
            }
        }
//        mGroupProfileView.setGroupIdText(DemoUtils.getGroupShortId(mGroup.getGroupId()));

//
//        mNotice.setText(mGroup.getDeclare());
//        mNotice.setSelection(mNotice.getText().length());


    }

    @Override
    public void clickLoadMoreData() {
        toRequest(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT);
    }

    @Override
    public void toRequest(int eventTag) {
        if(eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT){
            //刷新

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                swipeRefreshLayout.setRefreshing(false);
                return;
            }

            mCurrentPage = 1;

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "999");

            iCommonRequestPresenter.request(ApiConstants.EventTags.REFRESH_LIST_EVENT, mContext, ApiConstants.Urls.GROUP_LIST, map);

        }else if(eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT){
            //加载更多

            if (isRequesting)
                return;

            if (!NetUtils.isNetworkAvailable(mContext)) {
                showToastShort(Contants.NetStatus.NETDISABLE);
                iLoadView.showErrorView(loadMoreView);
                return;
            }

            if (mResultList.size() < ApiConstants.Request.PAGE_NUMBER) {
                return;
            }

            mCurrentPage++;

            iLoadView.showLoadingView(loadMoreView);

            RequestParams map = new RequestParams();
            map.put("page", "" + mCurrentPage);
            map.put("pageSize", "30");

            iCommonRequestPresenter.request(ApiConstants.EventTags.LOAD_MORE_LIST_EVENT, mContext, ApiConstants.Urls.GROUP_LIST, map);
        }
    }

    @Override
    public void getRequestData(int eventTag, String result) {
        if(eventTag == ApiConstants.EventTags.REFRESH_LIST_EVENT){
            Log.e("result",result);
            PreferenceUtils.setPrefString(this, Contants.Preference.GROUP,result);
            //下拉刷新

            List<Group> resultList = parseResult(result);

            mResultList.clear();

            mResultList.addAll(resultList);
            mResultList.addAll(discussionGroups);
            refreshListView();

        }else if(eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT){
            Log.e("result",result);
            PreferenceUtils.setPrefString(this, Contants.Preference.GROUP,result);
            //加载更多

            List<Group> resultList = parseResult(result);

            mResultList.addAll(resultList);

            adapter.notifyDataSetChanged();
        }
    }



    /**
     * 解析结果
     *
     * @param result
     * @return
     */
    public List<Group> parseResult(String result) {
        JsonHelper<Group> dataParser = new JsonHelper<Group>(
                Group.class);
        return dataParser.getDatas(
                result, "list");
    }

    @Override
    public void onRequestSuccessException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void onRequestFailureException(int eventTag, String msg) {
        if (eventTag == ApiConstants.EventTags.LOAD_MORE_LIST_EVENT) {

            if (mCurrentPage > 1)
                mCurrentPage--;

            iLoadView.showErrorView(loadMoreView);
        }

        showToastShort(msg);
    }

    @Override
    public void isRequesting(int eventTag, boolean status) {
        isRequesting = status;

        if (!status) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }
}
